package com.lwx.service;

import com.lwx.pojo.ExportBaseDTO;
import com.lwx.pojo.ExportColumn;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import sun.util.calendar.CalendarUtils;

import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.lang.annotation.Annotation;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.List;

public class ExportUtil  {
    //1.通过查询得到数据

    //2.将数据写在服务器上
    public String exportExcel(List data, ExportBaseDTO exportBaseDTO){
        Workbook workbook =new HSSFWorkbook();
        String fileName = getFileName(exportBaseDTO);
        Sheet sheet = workbook.createSheet(fileName);

        //创建列头
        Row titleRow = sheet.createRow(0);
        if(exportBaseDTO != null && exportBaseDTO.getExportClazz() != null){
            Class exportClazz = exportBaseDTO.getExportClazz();
            Annotation[] annotations = exportClazz.getAnnotations();
            for(Annotation annotation :annotations){
                if(ExportColumn.class.equals(annotation.getClass())){
                    ExportColumn exportColumn = (ExportColumn) annotation;
                    titleRow.createCell(exportColumn.seqNo());
                }

            }
        }
        String filePath = "";
        try {
            OutputStream fileOut = new FileOutputStream(filePath);
            workbook.write(fileOut);
            return filePath;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }


    public String getFileName(ExportBaseDTO exportBaseDTO){
        if(exportBaseDTO != null){
            String fileName = "";
            SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddhhmmss");
            fileName = sdf.format(Calendar.getInstance().getTime());
            return fileName;
        }
        return null;
    }
    //3.将服务器的地址返回
}
